<template>
    <div class="container">
        <div class="head">
            <span>{{ t('yl.menuSetting') }}</span>
            <a-button type="primary" :disabled="disabled" @click="handleSubmit">{{ t('yl.save') }}</a-button>
        </div>
        <div class="body">
            <div class="container">
                <a-tree
                    v-model:checkedKeys="businessSelectedRowKeys"
                    checkable
                    style="width: 100%"
                    :tree-data="treeData"
                    :dropdownClassName="'yl-treeselect'"
                    @check="onBusinessSelectChange"
                />
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, watch, reactive, toRefs, computed } from 'vue';
import useMenus, { useMenusbuild } from '@/hooks/useMenus';
import { useI18n } from 'vue-i18n';

export default defineComponent({
    name: 'treeselectMenu',
    props: ['value', 'checkedItem'],
    setup(props, { emit }) {
        const { t } = useI18n();
        //    console.log('所有节点包含半勾选父节点', allSelectedNodes);
        //     console.log('所有节点不包含半勾选父节点', businessSelectedRowKeys);
        const state = reactive({
            businessSelectedRowKeys: props.value,
            allSelectedNodes: [],
            treeData: [] as TreeDataItem[],
            treeKys: [],
            disabled: computed(() => {
                return props.checkedItem ? false : true;
            }),
        });

        // 监听checkedItem改变 重新赋值businessSelectedRowKeys
        watch(
            () => props.checkedItem,
            (newValue) => {
                if (!newValue) {
                    return (state.businessSelectedRowKeys = []);
                }
                state.allSelectedNodes = newValue.menus.length
                    ? newValue.menus.map((item: { id: string | number }) => Number(item.id))
                    : [];

                state.businessSelectedRowKeys = compareItem(state.allSelectedNodes, state.treeKys);
                // console.log(state.businessSelectedRowKeys);
            }
        );
        // 更新值
        watch(
            () => state.businessSelectedRowKeys,
            (newValue) => {
                emit('update:value', newValue);
            }
        );
        onMounted(() => {
            handleInitDepts();
        });

        // 获取所有部门
        const handleInitDepts = async () => {
            const params = {
                needId: true,
            };
            const { list } = await useMenusbuild(params);
            if (!list.length) return;
            state.treeData = TreeFun(list);
        };
        // 递归改树形结构数据
        const TreeFun = (list: any) => {
            let TreeList = list.map((item: any) => {
                return {
                    title: item.label,
                    key: item.id,
                    value: item.id,
                    isLeaf: item.leaf,
                    children: item.children && item.children.length ? TreeFun(item.children) : (state.treeKys.push(item.id), []),
                };
            });
            return TreeList;
        };

        // 2.将后台返回的含有父节点的数组和第一步骤遍历的数组做比较
        // 3.如果有相同值，将相同值取出来，push到一个新数组中
        const compareItem = (all_data: any, child_data: any) => {
            let uniqueChild = [];
            for (var i in child_data) {
                for (var k in all_data) {
                    if (all_data[k] === child_data[i]) {
                        uniqueChild.push(all_data[k]);
                    }
                }
            }
            console.log(uniqueChild);
            return uniqueChild;
        };

        // 异步加载树节点
        // const onLoadData = (treeNode: { [x: string]: any }) => {
        //     return new Promise(async (resolve: (value?: unknown) => void) => {
        //         const { key } = treeNode.dataRef;
        //         const params = {
        //             pid: key,
        //         };
        //         let { list } = await useMenus(params);
        //         if (!list.length) {
        //             return resolve();
        //         }
        //         list = list.map((item) => {
        //             return {
        //                 title: item.label,
        //                 key: item.id,
        //                 value: item.id,
        //                 isLeaf: item.leaf,
        //                 pId: key,
        //             };
        //         });
        //         treeNode.dataRef.children = list;
        //         resolve();
        //     });
        // };

        // 保存
        const handleSubmit = () => {
            // console.log(state.businessSelectedRowKeys);
            const obj = {
                ...props.checkedItem,
                menus: state.allSelectedNodes.length
                    ? state.allSelectedNodes.map((item: NormalObj) => {
                          return { id: item };
                      })
                    : [],
            };
            emit('menusEdit', obj);
        };

        const onBusinessSelectChange = (selectedKeys: any, info: any) => {
            // console.log('selectedKeys changed: ', selectedKeys);
            // console.log('info changed: ', info);
            // console.log(selectedKeys.concat(info.halfCheckedKeys));
            state.allSelectedNodes = selectedKeys.concat(info.halfCheckedKeys);
            // 已勾选子节点以及半勾选状态的父节点
            // this.allSelectedNodes = selectedKeys.concat(info.halfCheckedKeys);
            // this.businessSelectedRowKeys = selectedKeys;

            // console.log('所有节点包含半勾选父节点', this.allSelectedNodes);
            // console.log('所有节点不包含半勾选父节点', this.businessSelectedRowKeys);
        };
        return {
            ...toRefs(state),
            // onLoadData,
            compareItem,
            t,
            TreeFun,
            handleSubmit,
            onBusinessSelectChange,
        };
    },
});
</script>
<style lang="scss" scoped>
.container {
    background: $white;
    .head {
        z-index: 10;
        @include flex;
        justify-content: space-between;
        align-items: center;
        position: sticky;
        top: 0;
        left: 0;
        right: 0;
        padding: $width10 0;
        border-bottom: $bottom-border;
        background: $white;
    }
}
</style>
